package com.studio77.guessLyric.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.util.Base64;
import android.util.Log;

import com.studio77.guessLyric.MainActivity;
import com.studio77.guessLyric.core.StageManager;
import com.studio77.guessLyric.entity.QuestionEntity;

/**
 * 地图加载器
 * 
 * @author davelin
 * 
 */
public class WordMapLoader {
	public static void loadMap() {
		String fileName = "config.7z";

		try {
			InputStream is = MainActivity.instance.getAssets().open(fileName);
			InputStreamReader sr = new InputStreamReader(is, "UTF-8");
			BufferedReader br = new BufferedReader(sr, 1500);

			// 读取wordCount
			String line = br.readLine().trim();

			while (line != null && !line.trim().equals("")) {

				line = line.trim();
				// 解密
				String contentLine = new String(Base64.decode(line,
						Base64.DEFAULT), "UTF-8");
				String[] component = contentLine.split("#");
				if (component[0].equals("1")) {
					// 猜歌名
					if (component.length == 4) {
						QuestionEntity entity = new QuestionEntity();
						entity.setType(1);
						entity.setLyricStrList(component[2].split(","));
						entity.setSongName(component[3]);
						entity.setSinger(component[1]);
						if (entity.getSongName().length() <= 9) {
							StageManager.instance.Questions.add(entity);
						}
					} else {
						throw new Exception("config配置不正确");
					}
				} else if (component[0].equals("2")) {
					// 猜歌词
					if (component.length == 5) {
						QuestionEntity entity = new QuestionEntity();
						entity.setType(2);
						entity.setSongName(component[1]);
						entity.setSinger(component[2]);
						entity.setLyricStrList(component[3].split(","));
						entity.setGuessLyricIndex(Integer.parseInt(component[4]
								.trim()));

						if (entity.getGuessLyricIndex() > entity
								.getLyricStrList().length
								|| entity.getGuessLyricIndex() < 1) {
							throw new Exception("歌词index不正确");
						}
						if (entity.getLyricStrList()[entity
								.getGuessLyricIndex() - 1].length() <= 9
								&& entity.getLyricStrList()[entity
										.getGuessLyricIndex() - 1].indexOf(" ") < 0) {
							StageManager.instance.Questions.add(entity);
						}
					} else {
						throw new Exception("config配置不正确");
					}
				}
				line = br.readLine();
			}

			// 关闭Stream
			br.close();
			sr.close();
			is.close();
		} catch (Exception ex) {
			Log.e("loadmap", ex.getMessage(), ex);
		}
	}
}
